import 'dart:async';

import 'package:get/get.dart';
import 'package:nyh_motorcade_app/entity/user_info_entity.dart';
import 'package:nyh_motorcade_app/event/refresh_my_page_event.dart';
import 'package:nyh_motorcade_app/http/http_address.dart';
import 'package:nyh_motorcade_app/http/http_manager.dart';
import 'package:nyh_motorcade_app/utils/event_bus_utils.dart';
import 'package:nyh_motorcade_app/utils/sp_utils.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/multi_state/multi_state_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class MyController extends GetxController {
  late StreamSubscription event;
  RefreshController refreshController = RefreshController();
  MultiState multiState = MultiState.loading;
  String userName = "";
  String userIcon = "";
  String userPhone = "";
  String companyName = "";
  String companyCode = "";

  @override
  void onInit() {
    super.onInit();
    initEvent();
  }

  @override
  void onReady() {
    super.onReady();
    getUserInfo();
  }

  @override
  void onClose() {
    super.onClose();
    event.cancel();
  }

  void initEvent() {
    event = EventBusUtils.on<RefreshMyPageEvent>((event) {
      getUserInfo();
    });
  }

  void onRetry() {
    multiState = MultiState.loading;
    update();
    getUserInfo();
  }

  Future<void> onRefresh() async {
    getUserInfo();
  }

  Future<void> getUserInfo() async {
    String companyId = await SPUtils.getString(SPUtils.COMPANY_ID);
    httpManager.post(
      Get.context,
      HttpAddress.GET_USER_INFO,
      {"superId": companyId},
      isToast: true,
      onSuccess: (data) {
        if (data == null) {
          ToastUtils.toast("请求失败");
          if (refreshController.isRefresh) {
            refreshController.refreshFailed();
          }
          multiState = MultiState.fail;
          update();
          return;
        }
        UserInfoEntity userInfoEntity = UserInfoEntity().fromJson(data);

        userIcon = userInfoEntity.icon ?? "";
        userName = userInfoEntity.username ?? "";
        userPhone = userInfoEntity.loginPhone ?? "";
        companyName = userInfoEntity.companyName ?? "";
        companyCode = userInfoEntity.companyCode ?? "";

        if (refreshController.isRefresh) {
          refreshController.refreshCompleted();
        }
        multiState = MultiState.success;
        update();
      },
      onFail: (code, msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        }
        multiState = MultiState.fail;
        update();
      },
      onError: (msg) {
        if (refreshController.isRefresh) {
          refreshController.refreshFailed();
        }
        multiState = MultiState.error;
        update();
      },
    );
  }
}
